<?php

namespace app\api\service;

use think\facade\Db;
use think\facade\Queue;

class BalanceService
{
    /**
     *
     * 获取用户余额
     * */
    public static function getUserBalance($user_id)
    {
        $balance = Db::name('user')->where('user_id',$user_id)->value('balance');

        return $balance;
    }

    /**
     * 获取余额兑换金豆比例
     * */
    public static function getBalanceRedeemScale($store_id)
    {
        $balanceRedeemScale = Db::name('integral_setting')->where('store_id',$store_id)->value('gold_balance_scale');

        return  $balanceRedeemScale;
    }

    /**
     * 金豆兑换余额
     * */
    public static function reedBanlance($user_id,$gold_num,$balance)
    {
        Db::startTrans();
        try {
            Db::name('user')->where('user_id',$user_id)->dec('gold',$gold_num)->update();
            Db::name('user')->where('user_id',$user_id)->inc('balance',$balance)->update();

            Db::name('user_balance_detail')->insert([
                'user_id' => $user_id,
                'change_desc' => '金豆兑换余额',
                'change_type' => 1,
                'change_balance' => $balance,
                'change_time' => time()
            ]);


            Db::name('user_gold_detail')->insert([
                'user_id' => $user_id,
                'change_type' => 2,
                'change_desc' => '金豆兑换余额',
                'change_gold' => $gold_num,
                'change_time' => time()
            ]);
            Db::commit();
            return  true;
        }catch (\Exception $e){
            Db::rollback();
            return  false;
        }
    }

    /**
     * 余额变动记录
     * */
    public static function saveBalanceChangeRecord($data)
    {
        Db::name('user_integral_detail')->insert([
            'user_id' => $data['user_id'],
            'change_desc' => $data['change_desc'],
            'change_type' => $data['change_type'],
            'change_integral' => $data['change_integral'],
            'change_time' => time()
        ]);
    }

}